//
//  ImageEditContainer.swift
//  TemplateImageEditDemo
//
//  Created by liguandong on 2024/4/11.
//

import Foundation
import UIKit
import SnapKit
class TemplateEditContainer3: UIView {
    private var editingTemplateImageView : TemplateImageView3? = nil
    private var templateImageViewList = [TemplateImageView3]()
    
    private lazy var subViewParent: UIView = {
        let v = UIView()
        return v
    }()
    
    
    lazy var editView: TemplateEditView3 = {
        let v = TemplateEditView3()
        v.isHidden = true
        v.onTransformUpate = {[weak self] in
            if let self = self {
                self.editingTemplateImageView?.transform = v.transform
                self.editingTemplateImageView?.center = v.center
            }
        }
        v.onRemoveViewBlock = {[weak self] in
            if let self = self {
                self.templateImageViewList.removeAll { temp in
                    temp == self.editingTemplateImageView
                }
                self.editingTemplateImageView?.removeFromSuperview()
                self.editingTemplateImageView = nil
                self.editView.isHidden = true
            }
        }
        return v
    }()
    
    private lazy var panGesture: UIPanGestureRecognizer = {
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(panGestureAction(_:)))
        return panGesture
    }()
    
    private lazy var pinchGesture: UIPinchGestureRecognizer = {
        let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(pinchAction(_:)))
        pinchGesture.delegate = self
        return pinchGesture
    }()

    private lazy var rotateGesture: UIRotationGestureRecognizer = {
        let rotateGesture = UIRotationGestureRecognizer(target: self, action: #selector(rotateAction(_:)))
        rotateGesture.delegate = self
        return rotateGesture
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(subViewParent)
        subViewParent.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        addSubview(editView)
        editView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        addGestureRecognizer(panGesture)
        addGestureRecognizer(pinchGesture)
        addGestureRecognizer(rotateGesture)
     
    }
    
    func addTemplateImage(){
        let viewSize = getAddImageViewSize()
        let frame = CGRect(x: (bounds.size.width - viewSize.width) / 2.0,
                           y: (bounds.size.height - viewSize.height) / 2.0,
                           width: viewSize.width,
                           height: viewSize.height)
        let imageView = TemplateImageView3(frame: frame)
        imageView.image = addImage
        subViewParent.addSubview(imageView)
        templateImageViewList.append(imageView)
        
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(onImageTap(_:)))
        imageView.addGestureRecognizer(tapGesture)
        
        
        setEditingTemplateImage(imageView)
    }
    
    private func setEditingTemplateImage(_ imageView : TemplateImageView3){
        self.editView.isHidden = false
        self.editingTemplateImageView = imageView
        editView.resetState(imageView)
    }
   
    var addImage: UIImage = UIImage(named: "demoImg.jpg")!
    // Private Methods
    func getAddImageViewSize() -> CGSize {
        
        var width: CGFloat = 0
        var height: CGFloat = 0
        let defaultWH: CGFloat = 100
        
        if addImage.size.width > addImage.size.height {
            height = defaultWH
            width = (height * addImage.size.width / addImage.size.height)
        } else {
            width = defaultWH
            height = (width * addImage.size.height / addImage.size.width)
        }
        
        width += Ctrl_Radius * 2
        height += Ctrl_Radius * 2
        
        return CGSize(width: width, height: height)
    }
    
    
    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Gesture Recognizer Actions
    
    @objc private func onImageTap(_ tapGesture: UITapGestureRecognizer) {
        if tapGesture.view is TemplateImageView3 {
            setEditingTemplateImage(tapGesture.view as! TemplateImageView3)
        }
    }
    
    @objc func rotateAction(_ rotateGesture: UIRotationGestureRecognizer) {
        guard rotateGesture.numberOfTouches > 1 else {
            return
        }
        editView.rorateView(rotateGesture.rotation)
        rotateGesture.rotation = 0
    }
    
    @objc private func panGestureAction(_ panGesture: UIPanGestureRecognizer) {
        guard panGesture.state == .changed else { return }
        guard panGesture.numberOfTouches <= 1 else {
            panGesture.setTranslation(.zero, in: superview)
            return
        }
        let translation = panGesture.translation(in: superview)
        editView.translationView(x: translation.x, y: translation.y)
        panGesture.setTranslation(.zero, in: superview)
    }
    
    @objc private func pinchAction(_ pinchGesture: UIPinchGestureRecognizer) {
        guard pinchGesture.numberOfTouches > 1 else { return }
        let scale = pinchGesture.scale
        _ = editView.scaleView(scale)
        pinchGesture.scale = 1
    }
}

// MARK: - UIGestureRecognizerDelegate

extension TemplateEditContainer3: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
}
